import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  getRoleList,
  getRoleMenus,
  getRoleMenusByRoleId,
  addRole,
  updateRole,
  deleteRole,
  updateRoleStatus,
  assignMenuToRole
} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";

import { hasAuth, hasAuths } from "@/router/utils";

export function useRole(treeRef: Ref) {
  const form = reactive({
    roleName: "",
    roleCode: "",
    isActive: null,
    description: "",
    pageNumber: 1,
    pageSize: 10,
    orderBy: "Id",
    sortDirection: "Descending"
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };

  interface TreeNode {
    id: string;
    menuId: string;
    meta: any;
    name: string | null;
    parentId: string | null;
    path: string | null;
    redirect: string | null;
    component: string | null;
    children?: TreeNode[];
    level: number; // 新增的节点等级属性
    title: string;
  }

  function buildTree(menus: TreeNode[]): TreeNode[] {
    const map: { [key: string]: TreeNode } = {};
    const tree: TreeNode[] = [];

    menus.forEach(menu => {
      menu.title = menu?.meta?.title;
      map[menu.id] = menu;
      menu.children = [];
    });

    menus.forEach(menu => {
      if (menu.parentId !== null && map[menu.parentId]) {
        const parentLevel = map[menu.parentId].level || 0;
        menu.level = parentLevel + 1;
        map[menu.parentId].children.push(menu);
      } else {
        menu.level = 0;
        tree.push(menu);
      }
    });
    return tree;
  }

  function hasChildren(tree: TreeNode[], menuId: string): boolean {
    for (const node of tree) {
      if (node.parentId === menuId) {
        return true;
      }
      if (node.children && node.children.length > 0) {
        if (hasChildren(node.children, menuId)) {
          return true;
        }
      }
    }
    return false;
  }

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "roleId"
    },
    {
      label: "角色名称",
      prop: "roleName"
    },
    {
      label: "角色标识",
      prop: "roleCode"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          disabled={!hasAuth("role:roleid:status")}
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isActive}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "备注",
      prop: "description",
      minWidth: 160
    },
    {
      label: "创建时间",
      prop: "created",
      minWidth: 160,
      formatter: ({ created }) => dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation",
      hide: !hasAuths(["role:id", "role:delete:ids", "role:roleid:query:menu"])
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "!h-[20px]",
  //     "reset-margin",
  //     "!text-gray-500",
  //     "dark:!text-white",
  //     "dark:hover:!text-primary"
  //   ];
  // });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isActive === false ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.roleName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          await updateRoleStatus({
            roleId: row.roleId,
            concurrencyStamp: row.concurrencyStamp
          })
            .then(() => {
              message("修改成功", {
                type: "success"
              });
            })
            .catch(() => {})
            .finally(async () => {
              await onSearch();
            });
        }, 0);
      })
      .catch(() => {
        row.isActive === false ? (row.isActive = true) : (row.isActive = false);
      });
  }

  async function handleDelete(row) {
    await deleteRole({ roleIds: row.roleId });
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  async function handleSizeChange(val: number) {
    form.pageSize = val;
    await onSearch();
  }

  async function handleCurrentChange(val: number) {
    form.pageNumber = val;
    await onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getRoleList(toRaw(form));
    dataList.value = data.items;
    pagination.total = data.totalItems;
    //pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.roleId ?? "",
          roleId: row?.roleId ?? "",
          roleName: row?.roleName ?? "",
          roleCode: row?.roleCode ?? "",
          description: row?.description ?? "",
          concurrencyStamp: row?.concurrencyStamp ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        async function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              await addRole(curData);
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              await updateRole(curData);
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    isLinkage.value = true;
    const { id } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      const { data } = await getRoleMenusByRoleId({ roleId: id });
      const menuIds = data.map(x => x.menuId);

      const checkedKeys = [];
      menuIds.forEach(menuId => {
        if (!hasChildren(treeData.value, menuId)) {
          checkedKeys.push(menuId);
        }
      });
      treeRef.value.setCheckedKeys(checkedKeys);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-分配菜单 */
  async function handleSave() {
    const { id, title } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    const menuIds = treeRef.value.getCheckedKeys(); //选中
    const menuId2s = treeRef.value.getHalfCheckedKeys(); //半选中
    await assignMenuToRole({ roleId: id, menuIds: menuIds.concat(menuId2s) });
    message(`保存成功`, {
      type: "success"
    });
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    if (hasAuth("role:roleid:query:menu")) {
      const { data } = await getRoleMenus();
      treeIds.value = getKeyList(data, "id");
      treeData.value = buildTree(data);
    }
    onSearch();
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
